const PENDING = 'pending' // 等待
const FULFILLED = 'fulfilled' // 成功
const REJECTED = 'rejected' // 失败
class myPromise {
  constructor(executor) {
    executor(this.resolve,this.reject)
  }
  // 状态
  status = PENDING;
  // 成功之后的值
  value = undefined;
  // 失败之后的值
  reason = undefined;
  // 成功回调
  // successCallback = undefined;
  successCallback = [];
  // 失败回调
  // failCallback = undefined;
  failCallback = [];
  resolve = value => {
    console.log(1);
    // 如果状态不是等待，阻止程序向下执行
    if(this.status !== PENDING) return;
    this.status = FULFILLED;
    this.value = value
    // this.successCallback && this.successCallback(this.value)
    while(this.successCallback.length) this.successCallback.shift()(this.value)
  }
  reject = reason => {
    console.log(2);
    // 如果状态不是等待，阻止程序向下执行
    if(this.status !== PENDING) return;
    this.status = REJECTED;
    this.reason = reason
    // this.failCallback && this.failCallback(this.reason)
    while(this.failCallback.length) this.failCallback.shift()(this.reason)
  }
  then(successCallback, failCallback) {
    console.log(3);
    // 判断状态
    if(this.status === FULFILLED) {
      successCallback(this.value)
    } else if (this.status === REJECTED) {
      failCallback(this.reason)
    } else {
      // 等待
      // 将成功回调和失败回调存储起来
      // this.successCallback = successCallback
      // this.failCallback = failCallback

      this.successCallback.push(successCallback)
      this.failCallback.push(failCallback)
    }
  }
}

module.exports = myPromise